﻿using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml.Serialization;

namespace CodeSnippet.Helpers
{
    /// <summary>
    /// Provides helper methods to manage configuration-related elements.
    /// </summary>
    public static class ConfigHelper
    {
        #region Peristence
        /// <summary>
        /// Loads the contents of the given configuration file into the given configuration object.
        /// </summary>
        /// <typeparam name="T">Type of object to load.</typeparam>
        /// <param name="config">Object instance representing the contents to be populated.</param>
        /// <param name="configFile">Path and name of the configuration file to load.</param>
        /// <returns>Populated <c>config</c> object.</returns>
        /// <remarks>
        /// If <c>config</c> is <c>null</c>, a new instance of type <c>T</c> is created.
        /// </remarks>
        public static T LoadConfig<T>(T config, string configFile)
        {
            // Load the configuration.
            var serializer = new XmlSerializer(config.GetType());
            try
            {
                TextReader reader = new StreamReader(configFile);
                config = (T)serializer.Deserialize(reader);
                reader.Close();
            }
            catch (FileNotFoundException ex)
            {
                // Ignore the error. Use defaults.
                Debug.Write(string.Format(CultureInfo.InvariantCulture, "Unable to load configuration file. Using default values. Operation failed with the following error: {0}\r\n\r\n{1}", ex.Message, ex.StackTrace));
            }
            // Return the result of the operation.
            return config;
        }
        /// <summary>
        /// Stores the contents of the given configuration object in the given file location.
        /// </summary>
        /// <typeparam name="T">Type of object to load.</typeparam>
        /// <param name="config">Object instance representing the contents to be populated.</param>
        /// <param name="configFile">Path and name of the configuration file to load.</param>
        public static void StoreConfig<T>(T config, string configFile)
        {
            var serializer = new XmlSerializer(config.GetType());
            TextWriter writer = new StreamWriter(configFile);
            serializer.Serialize(writer, config);
            writer.Close();
        }
        #endregion Peristence
    }
}
